<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card class="box-card">
            <!-- 搜索与添加区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>

            <!-- 用户列表区域 -->
            <el-table :data="userList" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                    <!-- 作用域插槽 -->
                    <template slot-scope="scope">
                        <!-- scope.row为这一行上的所有数据 -->
                        <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                     <!-- 作用域插槽 -->
                    <template slot-scope="scope">
                        <!-- scope.row为这一行上的所有数据 -->
                        <el-tooltip class="item" effect="dark" content="编辑管理员信息" placement="bottom">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除管理员" placement="bottom">
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="角色分配" placement="bottom">
                            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[2, 5, 10, 15]"
                :page-size="5"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>

            <!-- 添加用户的对话框 -->
            <el-dialog
                title="添加管理员用户"
                :visible.sync="addDialogVisible"
                width="50%"
                @close="addDialogClosed">
                <!-- 内容主题区域 -->
                <span>
                    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="addForm.username"></el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input v-model="addForm.password" show-password></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="addForm.email"></el-input>
                        </el-form-item>
                        <el-form-item label="手机" prop="mobile">
                            <el-input v-model="addForm.mobile"></el-input>
                        </el-form-item>
                    </el-form>
                </span>
                <!-- 底部按钮区域 -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addUser">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 编辑用户的对话框 -->
            <el-dialog
                title="编辑管理员用户"
                :visible.sync="editDialogVisible"
                width="50%"
                @close="editDialogClosed">
                <!-- 内容主题区域 -->
                <span>
                    <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="editForm.username" :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="editForm.email"></el-input>
                        </el-form-item>
                        <el-form-item label="手机" prop="mobile">
                            <el-input v-model="editForm.mobile"></el-input>
                        </el-form-item>
                    </el-form>
                </span>
                <!-- 底部按钮区域 -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editUser">确 定</el-button>
                </span>
            </el-dialog>

        </el-card>
    </div>
</template>

<script>
export default {
    data(){
        // 校验邮箱的规则
        var checkEmail = (rule,value,cb) => {
            const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
            if(regEmail.test(value)){
                    return cb();
            }
            cb(new Error('请输入合法的邮箱'));
        }
        // 校验手机号的规则
        var checkMobile = (rule,value,cb) => {
            const regMobile = /^[1][3,4,5,7,8,9][0-9]{9}$/;
            if(regMobile.test(value)){
                    return cb();
            }
            cb(new Error('请输入合法的手机号'));
        }
        return{
            // 获取用户列表的参数对象
            queryInfo:{
                query:'',
                pagenum:1,
                pagesize:5
            },
            userList:[],
            total:0,
            // 添加用户对话框的显示与隐藏
            addDialogVisible:false,
            // 添加用户的表单数据
            addForm:{
                id:0,
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            // 添加用户的表单数据验证对象
            addFormRules:{
                username:[
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 50, message: '长度在 6 到 50 个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' },
                    { validator:checkEmail,trigger:'blur' }
                ],
                mobile:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { min: 5, max: 50, message: '长度在 5 到 50 个字符', trigger: 'blur' },
                    { validator:checkMobile,trigger:'blur' }
                ]
            },
            // 编辑用户对话框的显示与隐藏
            editDialogVisible:false,
            // 编辑用户的表单数据
            editForm:{
                username:'',
                email:'',
                mobile:''
            },
            // 编辑用户的表单数据验证对象
            // editFormRules:{
            //     email:[
            //         { required: true, message: '请输入邮箱', trigger: 'blur' },
            //         { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' },
            //         { validator:checkEmail,trigger:'blur' }
            //     ],
            //     mobile:[
            //         { required: true, message: '请输入手机号', trigger: 'blur' },
            //         { min: 5, max: 50, message: '长度在 5 到 50 个字符', trigger: 'blur' },
            //         { validator:checkMobile,trigger:'blur' }
            //     ]
            // },
        }
    },
    created(){
        // 发起首屏数据请求
        this.getUserList()
    },
    methods:{
        getUserList:async function(){
            const {data:res} = await this.$http.get('users',{params:this.queryInfo});
            //console.log(res);
            if(res.meta.status !== 200){
                return this.$message.error(res.meta.msg);
            }else{
                this.userList = res.data.users;
                this.total = res.data.total;
                // this.$message.success(res.meta.msg);
            }
        },
        // 监听pagesize改变的事件处理函数
        handleSizeChange:function(newSize){
            // console.log(newSize);
            this.queryInfo.pagesize = newSize;
            this.getUserList();
        },
        // 监听 页码值 改变的事件处理函数
        handleCurrentChange:function(newPage){
            // console.log(newPage);
            this.queryInfo.pagenum = newPage;
            this.getUserList();
        },
        // 监听 switch 状态的改变
        userStateChanged:async function(userInfo){
            //console.log(userInfo);
            const {data:res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
            if(res.meta.status !== 200){
                userInfo.mg_state = !userInfo.mg_state;
                return this.$message.error('更新用户状态失败!');
            }else{
                return this.$message.success('更新用户状态成功!');
            }
        },
        // 监听 添加用户对话框的关闭事件
        addDialogClosed:function(){
            this.$refs.addFormRef.resetFields();
        },
        // 点击 添加新用户窗口的确定按钮
        addUser:function(){
            this.$refs.addFormRef.validate(async valid => {
                if(!valid) return;
                // 发起添加用户的请求
                const {data:res} = await this.$http.post('users',this.addForm);
                if(res.meta.status!==201) return this.$message.error("添加失败！");
                this.$message.success("添加成功！");
                // 隐藏添加用户的对话框
                this.addDialogVisible = false;
                // 刷新用户列表
                this.getUserList();
            })
        },
        // 展示编辑用户的对话框
        showEditDialog:async function(id){
            const {data:res} = await this.$http.get('users/'+id);
            if(res.meta.status!==200){
                return this.$message.error('查询用户数据失败');
            }
            this.editForm = res.data;
            this.editForm.id = id;
            this.editDialogVisible = true;
        },
        // 编辑用户
        editUser:function(id){
            this.$refs.editFormRef.validate(async valid => {
                if(!valid) return;
                // 发起编辑用户的请求
                const {data:res} = await this.$http.put('users/'+this.editForm.id,this.editForm);
                if(res.meta.status!==200) return this.$message.error("编辑失败！");
                this.$message.success("编辑成功！");
                // 隐藏添加用户的对话框
                this.editDialogVisible = false;
                // 刷新用户列表
                this.getUserList();
            })
        },
        // 监听 修改用户对话框的关闭事件
        editDialogClosed:function(){
            this.$refs.editFormRef.resetFields();
        },
        // 根据id删除用户
        removeUserById:async function(id){
            // 弹框询问用户是否删除
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(async () => {
                    const {data:res} = await this.$http.delete('users/'+id);
                    if(res.meta.status !==200){
                        this.$message({
                            type: 'error',
                            message: '删除失败'
                        });
                    }
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getUserList();
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });       
                }
            );
        }
    }
}
</script>

<style lang="scss" scoped>

</style>